//
//  ProductNew.m
//  Trading365
//
//  Created by Jason on 12-3-20.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CustomerContactAdd.h"
#import "QuotEditCell.h"
#import "RoundedRectImageCreater.h"


@implementation CustomerContactAdd
@synthesize table;

static CGFloat theKeyboardHeight = 216.0f;
static NSMutableDictionary *InfoNameDict;
static UIImage *imageData;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title=INFO_STRING_CUSTOMER_CONTACT_ADD;
    self.table.backgroundColor=BACKGROUND_COLOR;
    self.navigationItem.rightBarButtonItem.enabled=YES;
 
    NSArray *title_array = [[NSArray alloc] initWithObjects:@"照片",@"姓名",@"联系电话",@"邮件",@"备注",nil];
    self.InfoListTitle = title_array; 
    [title_array release];

    NSArray *name_title = [[NSArray alloc] initWithObjects:@"customer_contact_photo_id",@"contact_name",@"telephone",@"mail",@"remarks",nil];
    self.InfoListName = name_title; 
    [name_title release];
    
    InfoNameDict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [InfoNameDict setValue:@"" forKey:@"0,0"];//pic
    [InfoNameDict setValue:@"" forKey:@"0,1"];//@"姓名",
    [InfoNameDict setValue:@"" forKey:@"0,2"];//@"联系电话",
    [InfoNameDict setValue:@"" forKey:@"0,3"];//@"邮件",
    [InfoNameDict setValue:@"" forKey:@"0,4"];//@"备注"
    
    imageData = [UIImage imageNamed:PIC_INFO_DEFAULT_PEOPLE];
    tableFrame=self.table.frame;
    
    [self refreshData];
    [self.table reloadData];
        
    keyboardHeight = theKeyboardHeight - 49;

}

- (void)viewDidUnload
{
    
    [self setTable:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    ///////////////////////////
    [self.table reloadData];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {    
    [imageData release];
    
    [InfoNameDict release];
    [table release];
    [super dealloc];
}

#pragma mark - Table view data source
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 60;
    }
    else
        return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    NSUInteger section = 0;
    
    if (row==0) {
        static NSString *CellIdentifier = @"InfoImageCell";
        
        InfoImageCell* cell = (InfoImageCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil){
            NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"InfoImageCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
            
        }
        
        cell.picture.image = imageData;
        cell.picture.userInteractionEnabled=YES;
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(picture:)];
        [cell.picture addGestureRecognizer:singleTap];
        [singleTap release];
        
        cell.name.textAlignment =  UITextAlignmentRight;
        
        NSString* text = @"";
        if (row < [self.InfoListTitle count]) 
        {
            text = [self.InfoListTitle objectAtIndex:row];
        }
        
        cell.name.text = text;
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.backgroundColor = [UIColor clearColor];
        cell.backgroundView.backgroundColor = [UIColor clearColor];
        
        return cell;
        
    }
    
    static NSString *CellIdentifier = @"QuotEditCell";
    
    QuotEditCell* cell = (QuotEditCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil){
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"QuotEditCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        
    }
    
    [cell initEditBeginBlcok:^(NSString *txtValue,int section1,int row1)
     {
         NSString *tmp_v=[NSString stringWithString:txtValue];
         NSString *tmp_k=[NSString stringWithFormat:@"%d,%d",section1,row1];
         [InfoNameDict setValue:tmp_v forKey:tmp_k];
//         NSLog(@"InfoNameDict:%@",InfoNameDict);
     }];
    
    // Configure the cell...
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.backgroundColor = [UIColor clearColor];
    cell.backgroundView.backgroundColor = [UIColor clearColor];
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    cell.row = row;
    cell.section = section;
    //allow edit
    cell.textValue.userInteractionEnabled=YES;
    cell.textValue.delegate = (id)self;
    cell.textValue.tag = row;
    
    NSString* text = @"";
    if (row < [self.InfoListTitle count]) 
    {
        text = [self.InfoListTitle objectAtIndex:row];
    }
    cell.labName.text = text;
    
    if ([InfoNameDict count] > 0)
    {
        cell.textValue.text = [InfoNameDict objectForKey:[NSString stringWithFormat:@"%d,%d",section,row]];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.  
    
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{    
    return nil;
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)modalView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    if (buttonIndex > 1)
//        return;
    return;
    
    int type=buttonIndex;
    if ([[InfoType share] IsSimulator])
        type = 1;
    
    ProductTakePict *picture = [[ProductTakePict alloc] init];
    [picture setMyTitle:@"添加联系人图片"];
    [picture setFlagCameraPhotos:0];
    [picture initPictureBeginBlcok:^(NSDictionary *imgInfo,int typeFlag) {
        UIImage *newImage0 = [RoundedRectImageCreater createRoundedRectImage:[imgInfo objectForKey:UIImagePickerControllerOriginalImage] size: [[imgInfo objectForKey:UIImagePickerControllerOriginalImage] size] ];
        if (typeFlag == 0){
            imageData = [[UIImage alloc] initWithCGImage:newImage0.CGImage scale:1.0 orientation:UIImageOrientationRight];
        }else{
            imageData = [[UIImage alloc] initWithCGImage:newImage0.CGImage];
        }
        
    }];
    [self.navigationController pushViewController:picture animated:YES];
    
    [picture release];
    
}

#pragma mark - text delegate
//该方法为点击输入文本框要开始输入是调用的代理方法：就是把view上移到能看见文本框的地方
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    [UIView setAnimationDuration:0.40]; 
    self.table.frame = CGRectMake(tableFrame.origin.x,tableFrame.origin.y,tableFrame.size.width,tableFrame.size.height - 216 - 49-30);
    
    [self.table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:textField.tag inSection:0]
                      atScrollPosition:UITableViewScrollPositionBottom
                              animated:YES];  
    
    [UIView commitAnimations];
    
}

//该方法为完成输入后要调用的代理方法：虚拟键盘隐藏后，要恢复到之前的文本框地方
- (void)textFieldDidEndEditing:(UITextField *)textField{
    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    [UIView setAnimationDuration:0.40]; 
    self.table.frame = tableFrame;
    [UIView commitAnimations];
    
}

#pragma mark - 
#pragma mark - my func

-(void) OnPreExcute
{
//    [super OnPreExcute];
}

-(void) DoInBackground
{
    //
}

-(void) OnPostExcute
{
//    [super OnPostExcute];
}

-(void)refreshData
{    
//    [[[TaskManager Share] GetTaskByType:NewContact Delegate:self] Excute];
}


- (void)buttonTapped:(id)sender
{    
    //
}

-(void)picture:(id)sender{
//    UIActionSheet *styleAlert = [[UIActionSheet alloc] 
//                                 initWithTitle:@""
//                                 delegate:(id)self 
//                                 cancelButtonTitle:@"取  消"  //2
//                                 destructiveButtonTitle:nil
//                                 otherButtonTitles: @"照相机",//0
//                                 @"相册",                     //1
//                                 nil];
//    [styleAlert showFromTabBar:self.tabBarController.tabBar];
//    [styleAlert release];
}


-(void)save{
    NSString *alert=@"";

    if ([[InfoNameDict objectForKey:@"0,3"] length] < 1)
        alert=@"请输入联系人邮件.";
    
    if ([[InfoNameDict objectForKey:@"0,2"] length] < 1)
        alert=@"请输入联系人电话.";
    
    if ([[InfoNameDict objectForKey:@"0,1"] length] < 1)
        alert=@"请输入联系人名称.";
        
    if ([alert length]>0){
        UIAlertView *alertview=[[UIAlertView alloc] initWithTitle:@"提示" message:alert delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertview show];
        [alertview release];
        return;
    }    
    
    XmlRpc *xml = [[XmlRpc alloc] init];
    NSMutableDictionary *tmp;
    NSString *remarks=[NSString stringWithFormat:@"%@",[InfoNameDict objectForKey:@"0,4"]];
    
    if ([remarks isEqualToString:@"(null)"])
        remarks = [NSString stringWithString:@""];
    
    tmp = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
           [GUID getGUIDString],@"contract_id",
           parentID,@"customer_id",
           [InfoNameDict objectForKey:@"0,1"],@"contact_name",
           [InfoNameDict objectForKey:@"0,2"],@"telephone",
           [InfoNameDict objectForKey:@"0,3"],@"mail",
           remarks,@"remarks", nil];

    NSLog(@"tmp=%@",tmp);
    
    [xml SaveCustomerContract:tmp];
    
    [tmp release];
    
    [xml release];
    
    [myToast showWithText:@"Save OK."];
    self.navigationItem.rightBarButtonItem.enabled=NO;
    [[InfoType share] SetFlagFreshView:INFO_TYPE_VIEW_REFRESH];
}

@end
